import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:ls_work/bad_event/bad_event_ext.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../viewmodel/new_health/new_health_sign_view_model.dart';

typedef OnNumberValueChanged = Function(String value);

class InputNumberView extends StatefulWidget {
  List<HealthSignRequestData> healthItems;
  int position;
  double max;

  OnNumberValueChanged? onChangedListener;

  InputNumberView({required this.healthItems,this.position = 0,this.onChangedListener,this.max = 500.0});

  @override
  State<StatefulWidget> createState() => _InputNumberState();
}

class _InputNumberState extends State<InputNumberView> {
  late HealthSignRequestData currentItem;

  var position = 0;

  @override
  void initState() {
    super.initState();
    position = widget.position;
    setState(() {
      currentItem = widget.healthItems[position];
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: verticalWidget()).addToContainer(
        decoration: BoxDecoration(
            color: Colors.grey[100],
          // gradient: LinearGradient(colors: [
          //   Colors.orange[50]!,Colors.grey[100]!,Colors.grey[100]!
          // ],begin: Alignment.topLeft,end: Alignment.bottomRight),
            borderRadius: BorderRadius.vertical(top: 30.radius)),
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20));
  }

  Widget horizontalWidget(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 20,
        ),
        CommonText("${currentItem.titleName}(${currentItem.unit})",textSize: 24,fontWeight: FontWeight.bold),
        SizedBox(height: 20,),
        CommonText(currentItem.value,
            textColor: Colors.black,
            textSize: 28,
            fontWeight: FontWeight.bold,
            hintText: '请输入')
            .addToContainer(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 20.borderRadius),
            width: double.infinity,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15)),
        SizedBox(
          height: 30,
        ),
        Row(
          children: [
            numberContent("7").setWeight(1),
            numberContent("8").setWeight(1),
            numberContent("9").setWeight(1),
            widgetContent(Icon(
              Icons.backspace,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.reduce;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            numberContent("4").setWeight(1),
            numberContent("5").setWeight(1),
            numberContent("6").setWeight(1),
            widgetContent(Icon(
              Icons.add,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.addNumber;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            numberContent("1").setWeight(1),
            numberContent("2").setWeight(1),
            numberContent("3").setWeight(1),
            widgetContent(Icon(
              Icons.remove,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.reduceNumber;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            widgetContent(
                position>0? CommonText(
                  "上一项",
                  textSize: 17,
                  textColor: Colors.orange,
                ):Container()).onTap(() {
              if(position==0){
                return;
              }
              setState(() {
                position--;
                currentItem = widget.healthItems[position];
              });
            }).setWeight(1),
            numberContent("0").setWeight(1),
            numberContent(".").setWeight(1),
            widgetContent(
                position<widget.healthItems.length-1? CommonText(
                  "下一项",
                  textSize: 17,
                  textColor: Colors.orange,
                ):Container()).onTap(() {
              if(position>=widget.healthItems.length-1){
                return;
              }
              setState(() {
                position++;
                currentItem = widget.healthItems[position];
              });
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
      ],
    );
  }

  Widget verticalWidget(){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 20,
        ),
        CommonText("${currentItem.titleName}(${currentItem.unit})",textSize: 24,fontWeight: FontWeight.bold),
        SizedBox(height: 20,),
        CommonText(currentItem.value,
            textColor: Colors.black,
            textSize: 28,
            fontWeight: FontWeight.bold,
            hintText: '请输入')
            .addToContainer(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 20.borderRadius),
            width: double.infinity,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15)),
        SizedBox(
          height: 30,
        ),
        Row(
          children: [
            numberContent("7").setWeight(1),
            numberContent("8").setWeight(1),
            numberContent("9").setWeight(1),
            widgetContent(Icon(
              Icons.backspace,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.reduce;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            numberContent("4").setWeight(1),
            numberContent("5").setWeight(1),
            numberContent("6").setWeight(1),
            widgetContent(Icon(
              Icons.add,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.addNumber;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            numberContent("1").setWeight(1),
            numberContent("2").setWeight(1),
            numberContent("3").setWeight(1),
            widgetContent(Icon(
              Icons.remove,
              color: Colors.orange,
            )).onTap(() {
              setState(() {
                currentItem.value = currentItem.value.reduceNumber;
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
        SizedBox(
          height: 16,
        ),
        Row(
          children: [
            widgetContent(
                position>0? CommonText(
                  "上一项",
                  textSize: 17,
                  textColor: Colors.orange,
                ):Container()).onTap(() {
              if(position==0){
                return;
              }
              setState(() {
                position--;
                currentItem = widget.healthItems[position];
              });
            }).setWeight(1),
            numberContent("0").setWeight(1),
            numberContent(".").setWeight(1),
            widgetContent(
                position<widget.healthItems.length-1? CommonText(
                  "下一项",
                  textSize: 17,
                  textColor: Colors.orange,
                ):Container()).onTap(() {
              if(position>=widget.healthItems.length-1){
                return;
              }
              setState(() {
                position++;
                currentItem = widget.healthItems[position];
              });
            }).setWeight(1),
          ].insertWidget(SizedBox(
            width: 16,
          )),
        ),
      ],
    );
  }

  Widget numberContent(String number) {
    return AspectRatio(
      aspectRatio: 1,
      child: Text(
        number,
        style: TextStyle(color: Colors.black, fontSize: 29),
      ).addToContainer(
          alignment: Alignment.center,
          decoration:
              BoxDecoration(color: Colors.white, borderRadius: 5.borderRadius)),
    ).onTap(
      () {
        if (number.isNotEmpty) {
          if (currentItem.value.isEmpty) {
            if (number != '.') {
              setState(() {
                currentItem.value = currentItem.value.append(number);
                if((currentItem.value.toDouble()??0)>widget.max){
                  currentItem.value = widget.max.d.toString()??"";
                }
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }
            print("=========>${number}\n${currentItem.value}");
          } else {
            if (number == '.') {
              if (!currentItem.value.contains(".")) {
                setState(() {
                  currentItem.value = currentItem.value.append(number);
                  if((currentItem.value.toDouble()??0)>widget.max){
                    currentItem.value = widget.max.d.toString()??"";
                  }
                });
                if(widget.onChangedListener!=null){
                  widget.onChangedListener!(currentItem.value);
                }
              }
            } else {
              setState(() {
                currentItem.value = currentItem.value.append(number);
                if((currentItem.value.toDouble()??0)>widget.max){
                  currentItem.value = widget.max.d.toString()??"";
                }
              });
              if(widget.onChangedListener!=null){
                widget.onChangedListener!(currentItem.value);
              }
            }
          }
        }
      },
    );
  }

  Widget widgetContent(Widget widget) {
    return AspectRatio(
      aspectRatio: 1,
      child: widget.addToContainer(
          alignment: Alignment.center,
          decoration:
              BoxDecoration(color: Colors.white, borderRadius: 5.borderRadius)),
    );
  }
}

Future<String?> showHealthNumberInput(BuildContext context,{ required List<HealthSignRequestData> healthItems,int position = 0,OnNumberValueChanged? onChangedListener}) async {
  return await showModalBottomSheet(
      context: context,
      builder: (context) {
        return InputNumberView(healthItems: healthItems,position: position,onChangedListener: onChangedListener,);
      },
      enableDrag: false,
      isScrollControlled: true,
      backgroundColor: Colors.transparent);
}

extension InputNumberExt on String {
  String append(String text) {
    return "${this}${text}";
  }

  String get reduce {
    return this.isEmpty ? "" : this.substring(0, length - 1);
  }

  String get addNumber {
    if (this.isEmpty) {
      return "";
    } else {
      var value = num.parse(this);
      return (value + 1).toString();
    }
  }

  String get reduceNumber {
    if (this.isEmpty) {
      return "";
    } else {
      var value = num.parse(this);
      return (value - 1).toString();
    }
  }
}
